﻿namespace Resharper.Abstractions.CodeDom.Statements.Blocks
{
  using System;
  using JetBrains.Annotations;
  using JetBrains.ReSharper.Psi.CSharp.Tree;
  using Resharper.Abstractions.Actions;
  using Resharper.Abstractions.Shell;

  /// <summary>Defines the <see cref="StatementExtensions"/> class.</summary>
  public static class BlockExtensions
  {
    #region Public Methods

    /// <summary>Gets the selected statement.</summary>
    /// <param name="statement">The statement.</param>
    /// <returns>Returns the selected statement.</returns>
    [CanBeNull]
    public static Block GetContainingBlock([NotNull] this Statement statement)
    {
      if (statement == null)
      {
        throw new ArgumentNullException("statement");
      }

      var result = statement.InternalStatement.GetContainingNode<IBlock>();

      return result != null ? new Block(result) : null;
    }

    /// <summary>Gets the containing block.</summary>
    /// <param name="dataContext">The data context.</param>
    /// <returns>Returns the containing block.</returns>
    [CanBeNull]
    public static Block GetContainingBlock([NotNull] this DataContext dataContext)
    {
      if (dataContext == null)
      {
        throw new ArgumentNullException("dataContext");
      }

      var result = dataContext.GetSelectedElement<IBlock>();

      return result != null ? new Block(result) : null;
    }

    /// <summary>Creates the empty block.</summary>
    /// <param name="factory">The factory.</param>
    /// <returns>Returns the empty block.</returns>
    [NotNull]
    public static Block CreateEmptyBlock(this Factory factory)
    {
      return new Block(factory.InternalFactory.CreateEmptyBlock());
    }

    #endregion
  }
}